// Copyright 2007 Helsinki Institute for Information Technology
// and the authors.
//
// Authors: Ken Rimey <rimey@hiit.fi>

// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

// XXX Put clickable pencil icon next to captions and title.
// XXX Change cursor over clickable objects.
// XXX Add navigation back to admin page or list of albums.

onload = function() {
    document.body.innerHTML =
        '<div id="header" align="center"></div>'
        + '<div id="content"></div>'
        + '<table width="100%"><tr>'
        + '<td><div id="left_footer"></div></td>'
        + '<td align="right"><div id="right_footer"></div></td>'
        + '</tr></table>';

    var q = get_params();
    if (q.config) {
        configuration.init();
    } else if (q.slide) {
        slideshow.init(Number(q.slide));
    } else {
        overview.init();
    }
};

var collection = location.pathname.split('/')[2];

var overview = {
    title: '',
    mark: 0,
    total: 0,
    interval: 2000,

    init: function() {
        $('header').innerHTML = '<h1 id="title"></h1>';
        $('title').onclick = this.ask_title.bind(this);

        var url = '/collection/' + collection;
        url += '?next=/collection/' + collection + '/web/index.html';
        $('left_footer').innerHTML = '<br/>'
            + '<form id="upload_form" method="post" enctype="multipart/form-data">'
            + '<input type="file" name="put_file_under_name:file" />'
            + '<br/><input type="submit" value="Upload" />'
            + '</form>';
        $('upload_form').setAttribute('action', url);

        $('right_footer').innerHTML =
            '<a href="?config=true">Configure this photo album</a><br/>'
            + '<a href="javascript:create_new_album()">Create a new photo album</a>';

        this.update();
    },

    ask_title: function() {
        var new_title = prompt('Enter a new title:', this.title);
        if (new_title) {
            put('../info/title', new_title, this.fetch_title.bind(this));
        }
    },

    update: function() {
        this.fetch_title();
        this.fetch_images();
    },

    fetch_title: function() {
        this.title = get('../info/title?output=text&timeout=0') || '';
        document.title = this.title || 'Untitled Photo Album';
        set_text('title', this.title || 'Click Here to Set Title');
    },

    fetch_images: function() {
        var url = '../file/?output=json&keys_only=true&last_mark=' + this.mark;
        var result = eval('(' + get(url) + ')');
        var filenames = result.keys;
        this.mark = result.mark;
        for (var i = 0; i < filenames.length; i += 1) {
            this.add_image('../file/' + filenames[i]);
        }
        this.update_again();
    },

    add_image: function(url) {
        this.total += 1;

        var img = document.createElement('img');
        img.setAttribute('src', url);
        img.setAttribute('width', '240');
        img.setAttribute('border', '0');
        img.setAttribute('hspace', '10');
        img.setAttribute('vspace', '10');

        var a = document.createElement('a');
        a.setAttribute('href', '?slide=' + this.total);
        a.appendChild(img);

        $('content').appendChild(a);
    },

    update_again: function() {
        setTimeout(this.update.bind(this), this.interval);
        this.interval *= 2;
    }
};

var slideshow = {
    slide: 0,                   // Slides are numbered 1..total.
    total: 0,
    filenames: [],
    editing_description: false,

    init: function(n) {
        this.slide = n;

        $('header').innerHTML =
            '<img id="left_arrow" src="/static/icons/gray_left_arrow.gif" />'
            + ' <img id="up_arrow" src="/static/icons/gray_up_arrow.gif" />'
            + ' <img id="right_arrow" src="/static/icons/gray_right_arrow.gif" />';
        $('up_arrow').onclick = function() { location = 'index.html'; };

        $('content').innerHTML =
            '<a id="anchor" href=""><img id="image" src="" height="480" border="0" /></a>'
            + '<div id="description" style="width:60%"><div/>';
        $('content').setAttribute('align', 'center');

        var result = eval('(' + get('../file/?output=json&keys_only=true') + ')');
        this.filenames = result.keys;
        this.total = this.filenames.length;

        var self = this;
        $('left_arrow').onclick = function() { self.go(self.slide - 1); };
        $('right_arrow').onclick = function() { self.go(self.slide + 1); };

        this.go(this.slide);
    },

    go: function(n) {
        if (n < 1) { n = 1; }
        if (n > this.total) { n = this.total; }

        this.slide = n;
        this.filename = this.filenames[n - 1];

        document.title = n + ' / ' + this.total;

        var url = '../file/' + this.filename;

        // Removing and reinserting the img element avoids image
        // scaling problems in Safari.
        var node = $('anchor').removeChild($('image'));
        node.setAttribute('src', url);
        $('anchor').appendChild(node);

        $('anchor').setAttribute('href', url);

        var left = (n > 1)
            ? '/static/icons/gray_left_arrow.gif'
            : '/static/icons/white_left_arrow.gif';
        var right = (n < this.total)
            ? '/static/icons/gray_right_arrow.gif'
            : '/static/icons/white_right_arrow.gif';
        $('left_arrow').setAttribute('src', left);
        $('right_arrow').setAttribute('src', right);

        $('description').innerHTML = '';
        $('description').onclick = this.edit_description.bind(this);
        this.update_description();
    },

    edit_description: function() {
        this.editing_description = true;
        this.update_description();
    },

    update_description: function() {
        var text = get('../meta/' + this.filename + '?output=text&timeout=0');
        set_text('description', text || 'Click here to set caption');
        if (this.editing_description) {
            this.editing_description = false;
            this.ask_description(text);
        }
    },

    ask_description: function(text) {
        var new_text = prompt('Edit caption:', text || '');
        if (new_text != null) {
            put('../meta/' + this.filename, new_text,
                this.update_description.bind(this));
        }
    }
}

var configuration = {
    init: function() {
        var self = this;

        document.title = 'Photo Album Configuration';
        $('header').innerHTML = '<h1>Photo Album Configuration</h1>';

        var groups = this.get_groups();
        for (var i = 0; i < groups.length; i += 1) {
            var group = groups[i];
            var url = '/collection/' + group;
            var title = get(url + '/info/title?output=text&timeout=0') || group;

            var id = 'group' + i;
            var html = '<p>Annotation is enabled for friends of '
                + '<a id="' + id + '" href=""></a>.</p>';
            new Insertion.Bottom('content', html);
            $(id).setAttribute('href', url + '/web/index.html');
            $(id).appendChild(document.createTextNode(title));
        }

        if (groups.length == 0) {
            var html = '<p>Annotation by others is disabled.</p>';
            html += '<p><input type="button" id="enable" value="Enable Annotation" /></p>';
            new Insertion.Bottom('content', html);
            $('enable').onclick = function() { self.enable(); };
        } else {
            var html = '<p><input type="button" id="disable" value="Disable Annotation" /></p>';
            new Insertion.Bottom('content', html);
            $('disable').onclick = function() { self.disable_all(); };
        }

        new Insertion.Bottom('content', '<hr/>');

        $('left_footer').innerHTML = '<a href="index.html">Return to thumbnail page</a>';
    },

    enable: function(group, role) {
        if (!group) {
            var info = eval('(' + get('/info?output=json') + ')');
            group = info.default_profile;
        }

        if (!role) {
            role = 'friend';
        }

        var url = '../rights/0x' + group + '/' + role + '/put/meta';
        put(url, '1', function() { location.reload(); });
    },

    disable_all: function() {
        var result = eval('(' + get('../rights/?output=json') + ')');
        var data = result.data;
        for (var i = 0; i < data.length; i += 1) {
            var k = data[i][0];
            var v = data[i][1];
            if (v == '1') {
                put('../rights/' + k, '0');
            }
        }

        location.reload();
    },

    get_groups: function() {
        var result = eval('(' + get('../rights/?output=json') + ')');
        var data = result.data;

        var groups = [];
        for (var i = 0; i < data.length; i += 1) {
            var k = data[i][0];
            var v = data[i][1];
            if (v == '1') {
                var slash = k.indexOf('/');
                var group = k.substring(2, slash); // Skip leading "0x".
                if (k.substring(slash) == '/friend/put/meta') {
                    groups.push(group);
                }
            }
        }

        return groups;
    }
};

function create_new_album() {
    var html = get('index.html');
    location = '/?create_collection=true'
        + '&put:info/title='
        + '&put:info/type=tag:hiit.fi,2007-04:photo_album'
        + '&put:web/index.html=' + encodeURIComponent(html);
}

function set_text(id, text) {
    var node = $(id);
    while (node.hasChildNodes()) {
        node.removeChild(node.firstChild);
    }
    node.appendChild(document.createTextNode(text));
}

function get_params() {
    var result = {};

    var q = location.search;
    if (q.length > 1) {
        q = q.substring(1, q.length);

        var fields = q.split('&');
        for (var i = 0; i < fields.length; i += 1) {
            var parts = fields[i].split('=');
            var key = parts[0];
            var value = parts[1];
            result[key] = decodeURIComponent(value);
        }
    }

    return result;
}

function get(url, callback) {
    var options = { method: 'get' };
    options.asynchronous = !!callback;
    if (callback) { options.onSuccess = callback; }

    var request = new Ajax.Request(url, options);
    if (!callback) {
        return request.success() ? request.transport.responseText : null;
    }
}

function put(url, value, callback) {
    var options = {
        requestHeaders: { 'X-HTTP-Method-Override': 'PUT' },
        method: 'post',
        postBody: value,
        contentType: 'application/octet-stream',
        onFailure: function() { alert('Sorry, unauthorized.'); }
    };

    options.asynchronous = !!callback;
    if (callback) { options.onSuccess = callback; }

    new Ajax.Request(url, options);
}
